﻿Imports System.DirectoryServices
Imports System.Configuration
Imports System.Web.Security
Imports System.Web.UI.DataSourceControl
Imports System
Imports System.Xml
Imports System.Data
Imports System.Data.SqlClient

Partial Class Default2
    Inherits System.Web.UI.Page
    Dim con As New DBConnect


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'connecting using httpS.
        If Not HttpContext.Current.Request.Url.AbsoluteUri.StartsWith("ht tp://localhost") Then
            If HttpContext.Current.Request.IsSecureConnection = False Then
                Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri.Insert(4, "s")
                Response.Redirect(url)
            End If
        End If


        '----

        Context.Request.Browser.Adapters.Clear()
        Dim strRemoteIP As String, strRemoteOS As String
        strRemoteIP = Request.ServerVariables("REMOTE_ADDR")
        strRemoteOS = Request.ServerVariables("HTTP_USER_AGENT")
        If Len(strRemoteIP) > 1 Then
            LabelIP.Text = "IP Address Of Your Computer: " & strRemoteIP
        Else
            LabelIP.Text = "IP Address Of Your Computer: UNDETERMINED"
        End If
        Page.RegisterStartupScript("SetFocus", "<script>document.getElementById('" & TextBoxUID.ClientID & "').focus();</script>")
    End Sub

    Protected Sub ButtonLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonLogin.Click
        Dim anUser As String = TextBoxUID.Text.Trim
        Dim apassword As String = TextBoxPWD.Text.Trim
        Dim RetVal As String
        Dim result As Integer
        Select Case anUser.ToUpper()
            Case "GUEST"
                RetVal = "Guest"
            Case Else
                RetVal = AuthenticateUser(anUser, apassword)
        End Select
        If Len(RetVal) > 0 Then

            Session("UserID") = TextBoxUID.Text.Trim
            Dim accessNetID = TextBoxUID.Text.Trim
            Session("UserPWD") = TextBoxPWD.Text.Trim
            Session("UserIn") = "yes"
            'determine if admin ,super , or regular student
            Dim SqlConnectString As String = con.SqlConnectString
            Dim myConnection As New SqlConnection(SqlConnectString)
            Dim myCommand As New SqlCommand()
            ' Dim result As Integer
            myCommand.Connection = myConnection
            'Set the SQLCommand object's properties for executing a Stored Procedure
            myCommand.CommandType = CommandType.StoredProcedure
            myCommand.CommandText = "AccessLevel"       'Name of the Stored Procedure to execute

            Dim inputParameter As New SqlParameter("@accessNetID", accessNetID)
            inputParameter.Direction = ParameterDirection.Input
            myCommand.Parameters.Add(inputParameter)

            Dim returnParameter As New SqlParameter("@new_identity", 0)
            returnParameter.Direction = ParameterDirection.Output
            myCommand.Parameters.Add(returnParameter)

            Try
                myConnection.Open()
                myCommand.ExecuteReader()
            Catch ex As Exception
                Throw ex
            Finally

                If Not IsDBNull(myCommand.Parameters("@new_identity").Value) Then
                    result = CType(myCommand.Parameters("@new_identity").Value, Integer)

                    If result = 2 Then
                        Response.Redirect("viewStudents.aspx")
                        Session("userType") = 2
                    ElseIf result = 3 Then
                        Response.Redirect("viewStudents3.aspx")
                        Session("userType") = 3
                    Else
                        Session("userType") = 1
                        Response.Redirect("ViewStudentFromStudentSide.aspx")
                    End If
                Else
                    Session("userType") = 1
                    Response.Redirect("ViewStudentFromStudentSide.aspx")
                End If
                myConnection.Close()
                myConnection.Dispose()
            End Try
            Response.Redirect("ViewStudentFromStudentSide.aspx", False)
        Else
            lblLoginFail.Visible = True
        End If
    End Sub

    Public Shared Function getDNFromLDAP(ByVal strUID As String) As String
        Dim entry As New DirectoryEntry("LDAP://rock.temple.edu/ou=temple,dc=tu,dc=temple,dc=edu")
        entry.AuthenticationType = AuthenticationTypes.None
        Dim mySearcher As New DirectorySearcher(entry)
        entry.Close()
        entry.Dispose()
        mySearcher.Filter = "(sAMAccountName=" + strUID + ")"
        Dim result As SearchResult = mySearcher.FindOne()
        mySearcher.Dispose()
        Dim nIndex As Integer = result.Path.LastIndexOf("/")
        Dim strDN As String = result.Path.Substring((nIndex + 1)).ToString().TrimEnd()
        Return strDN
    End Function 'getDNFromLDAP

    Function AuthenticateUser(ByVal strUID As String, ByVal strPassword As String) As String
        Dim strID As String = String.Empty
        Dim entry As New DirectoryEntry

        Try
            ' call getDNFRromLDAP method to anonymously (port 389)
            ' search against ldap for the correct DN
            Dim strDN As String = getDNFromLDAP(strUID)

            'now use the found DN for the secure bind (port 636)
            entry.Path = "LDAP://rock.temple.edu/" + strDN
            entry.Username = strDN
            entry.Password = strPassword
            entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer

            'try to fetch a property..if no errors raised then it works
            strID = entry.Properties("sAMAccountName")(0).ToString()

        Catch

        Finally
            entry.Close()
            entry.Dispose()
        End Try

        Return strID
    End Function 'AuthenticateUser

    Protected Sub TextBoxUID_TextChanged(sender As Object, e As EventArgs) Handles TextBoxUID.TextChanged

    End Sub
End Class